package com.shd.edanpei.presenter;

import android.text.TextUtils;

import com.shd.edanpei.base.BasePresenterImpl;
import com.shd.edanpei.base.network.api.ApiCreator;
import com.shd.edanpei.base.network.model.NoDataResponse;
import com.shd.edanpei.base.network.rx.BaseObserver;
import com.shd.edanpei.base.network.rx.RxTransformer;
import com.shd.edanpei.util.ToastUtil;
import com.shd.edanpei.enums.GenderEnum;
import com.shd.edanpei.presenter.contract.NewCustomerContract;

import java.io.File;

import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by mc on 2018/9/4.
 * yang-wen-wen
 */

public class NewCustomerPresenter extends BasePresenterImpl<NewCustomerContract.NewCustomerIView>
        implements NewCustomerContract.NewCustomerIPresenter {

    private String pictureUrl = "";


    public NewCustomerPresenter(NewCustomerContract.NewCustomerIView mView) {
        super(mView);
    }

    @Override
    public void uploadPicture(String picturePath) {
        ApiCreator.getApi().uploadPicture(createFileBody(picturePath), createStrBody("1"))
                .compose(RxTransformer.<String>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    protected void onSuccess(String data) {
                        pictureUrl = data;
                    }
                });
    }

    @Override
    public void submit(String name, String gender, String phone) {
        if (TextUtils.isEmpty(name)) {
            ToastUtil.showToast("请输入姓名");
            return;
        }
        if (!gender.equals(GenderEnum.male.getValue()) &&  !gender.equals(GenderEnum.female.getValue())) {
            ToastUtil.showToast("请选择性别");
            return;
        }
        if (TextUtils.isEmpty(phone)) {
            ToastUtil.showToast("请输入手机号");
            return;
        }
        ApiCreator.getApi().createFriend(pictureUrl, name, GenderEnum.getKey(gender), phone)
                .compose(RxTransformer.<NoDataResponse>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<NoDataResponse>() {
                    @Override
                    protected void onSuccess(NoDataResponse data) {
                        ToastUtil.showToast("新建成功");
                        mBaseIView.getContext().finish();
                    }
                });
    }

    private MultipartBody.Part createFileBody(final String pic) {
        File file = new File(pic);
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
        return MultipartBody.Part.createFormData("file", file.getName(), requestBody);
    }

    private RequestBody createStrBody(final String value) {
        return RequestBody.create(MediaType.parse("text/plain"), value);
    }

}
